package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.cl.picture_selector.ImagePicker
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.bean.Param
import com.jt.assistant.custom_view.ItemEdit
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.utils.ImageUtil
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_car_receive_upload.*
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**
 * 车辆交接单上报
 */
class CarReceiveUploadActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }
    private val maxPicCount = 5//最大图片选择数量
    override fun layoutId(): Int = R.layout.activity_car_receive_upload

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_carReceiverPic) {
            layoutManager = GridLayoutManager(context, 3)
            canScrollVertically(0)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
        ie_receiveDiff.mData.add("正常交接")
        ie_receiveDiff.mData.add("异常交接")
        ie_receiveDiff.setEditText("正常交接")
        if (!intent.getStringExtra(GlobalConfig.DELIVERYRECEIPTID).isNullOrEmpty()) {
            //选择运单号上传
            ie_car.visibility = View.GONE
        }
        ie_car.setTypeText(intent.getStringExtra(GlobalConfig.LICENCE).toString())
        ie_car.setEditText(intent.getStringExtra(GlobalConfig.DESCITYNAME).toString())
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.data[position].isEmpty()) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(maxPicCount - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@CarReceiveUploadActivity,
                        GlobalConfig.REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(
                    Intent(
                        this@CarReceiveUploadActivity,
                        PreActivity::class.java
                    ).apply {
                        putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                        putExtra("POSITION", position)
                    }, GlobalConfig.PIC_REQUEST
                )
            }
        }

        ie_receiveDiff.mEdit.setOnClickListener {
            ie_receiveDiff.showListDialog("是否存在差异", this)
        }

        ie_receiveDiff.setOnItemClickListener(object : ItemEdit.OnClickLister {
            override fun onItemClick(position: Int) {
                if (position == 0)
                    ie_receiveRemark.visibility = View.GONE
                else
                    ie_receiveRemark.visibility = View.VISIBLE
            }
        })

        bt_commit.setOnClickListener {

            if (ie_receiveDiff.mCurrentPosition == 1 &&
                ie_receiveRemark.mEdit.text.toString().isEmpty()
            ) {
                ToastUtils.showShort("请输入备注")
                return@setOnClickListener
            }

            if (mAdapter.data.size == 1) {
                ToastUtils.showShort("请选择图片")
                return@setOnClickListener
            }
            val params = Param::class.java.newInstance()

            if (intent.getStringExtra(GlobalConfig.DELIVERYRECEIPTID).isNullOrEmpty()) {//正常上传
                params.dispatchCarId =
                    intent.getStringExtra(GlobalConfig.DISPATCH_CAR_ID).toString()
                params.hasDiff = ie_receiveDiff.mCurrentPosition.toString()
                params.remark = ie_receiveRemark.mEdit.text.toString()
                params.type = intent.getStringExtra(GlobalConfig.CARTYPE).toString()
                viewModel.uploadDriverDeliveryReceipt(params, mAdapter.data)

            } else {//选择运单号上传
                params.deliveryReceiptId =
                    intent.getStringExtra(GlobalConfig.DELIVERYRECEIPTID).toString()
                params.remark = ie_receiveRemark.mEdit.text.toString() + ""
                viewModel.uploadDriverDeliveryImgUp(params, mAdapter.data)
            }

        }
         //正常上传
        viewModel.mUploadDriverDeliveryReceipt.observe(this, {
            log(it)
            if (it.isSuccess()) {
                speakString("上传成功")
                finish()
            }
        })
        //选择运单号上传
        viewModel.mUploadDriverDeliveryImgUp.observe(this, {
            log(it)
            if (it.isSuccess()) {
                speakString("上传成功")
                finish()
            }
        })

    }


    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                    if ((mAdapter.data.size - 1) == maxPicCount) {
                        mAdapter.data.remove("")
                        mAdapter.notifyDataSetChanged()
                    }
                }

                override fun onError(e: Throwable) {

                }
            }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GlobalConfig.REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePick(data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES))
        }

        if (requestCode == GlobalConfig.PIC_REQUEST && resultCode == RESULT_OK) {
            val picList = GsonUtils.fromJson<ArrayList<String>>(
                data!!.getStringExtra(GlobalConfig.PIC_RESULT),
                object : TypeToken<ArrayList<String>>() {}.type
            )
            imagePickPre(picList)
        }
    }

    private fun imagePickPre(picList: ArrayList<String>?) {
        mAdapter.data.clear()
        if (picList!!.isNotEmpty()) {
            mAdapter.data.addAll(picList)
        }
        mAdapter.data.add("")
        if ((mAdapter.data.size - 1) == maxPicCount) {
            mAdapter.data.remove("")
        }
        mAdapter.notifyDataSetChanged()
    }


}